package systemController

import (
	"net/http"
	"wisdomCoach/global"
	"wisdomCoach/model"
	"wisdomCoach/utils"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func GetRouters(cxt *gin.Context) {
	var (
		user model.User
		menu []model.Menu
	)
	userId := cxt.GetInt64("userId")
	if err := global.DB.Preload("Roles", func(db *gorm.DB) *gorm.DB {
		return db.Preload("Menus")
	}).Where("user_id = ?", userId).First(&user).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	for _, role := range user.Roles {
		menu = append(menu, role.Menus...)
	}
	treeMenu := utils.TreeMenu(utils.UniqueMenu(menu))

	cxt.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": treeMenu,
	})
}
